﻿cppei.install('iframcontrol');


function timer(func) {
    this.handle = null;
    this.isPause = false;
    this.func = func;
    this.start = function () {
       // console.log('timer is start');
        if (!this.handle) {
            this.handle = window.setInterval(function (inst) {
                inst.onTick();
            }, 10000, this);
            //this.handle = window.setInterval(func, 1000);
            // document.getElementById('output').innerHTML += 'start:' + this.handle + '<br/>';
        }

    }
    this.onTick = function () {
        if (!this.isPause) {
            if (this.func) {
                this.func();
            }
        }
    }
    this.onStop = function () {
        if (this.handle) {
            window.clearInterval(this.handle);
            this.handle = null;
        }
    }
    this.onPause = function () {
       // console.log('timer is pause');
        this.isPause = true;
    }
    this.onResume = function () {
      //  console.log('timer is begin');
        this.isPause = false;
    }
}

var app = angular.module('indexApp', []);
app.controller("indexController", function ($scope, $http, $q) {

    $scope.isLoading = true;
    $scope.loadingText = "正在加载信息...";
    $scope.viewStack = null;
    //左侧菜单活动的叶子节点
    $scope.activedLeafNode = null;

    //获取左侧菜单列表
    $scope.getNavList = function () {
        $scope.loadingText = "正在加载左侧菜单列表...";
        var prms = Promise();

        $http({
            method: 'get',
            url: cppei.api.getUrl('xweb','menu','get')
        }).success(function (result, status) {
            if (result.isSuccess) {
                $scope.items = result.data.items;
                $scope.addActive($scope.items);
                prms.resolve();
            }
            else {
                prms.reject();
            }

        }).error(function (result, status) {
            prms.reject();
        });
        return prms;
    }

    //获取标题和图标
    $scope.getApp = function () {
        $scope.loadingText = "正在加载标题和图标...";
        var prms = Promise();

        $http({
            method: 'get',
            url: cppei.api.getUrlWithTimespan('xweb', 'app', 'get'),//'/WebApi?sys:sno=AppAuth&sys:act=Create',
        }).success(function (result, status) {
            if (result.isSuccess) {
                $scope.appItem = {};
                $scope.appItem.logo = result.data.logo;
                $scope.appItem.name = result.data.name;

                document.title = result.data.name;

                prms.resolve();
            }
            else {
                prms.reject();
            }
        }).error(function (result, status) {
           // console.log('$scope.getApp error');
            prms.reject();
        });
        return prms;
    }

    //获取用户信息
    $scope.getUserProfile = function () {
        $scope.loadingText = "正在加载用户信息...";
       // console.log($scope.loadingText);
        var prms = Promise();

       // console.log('$scope.getUserProfile begin');
        $http({
            method: 'get',
            url: cppei.api.getUrlWithTimespan('Sys', 'GetUserProfile'),//'/WebApi?sys:sno=AppAuth&sys:act=Create',
        }).success(function (result, status) {
            //debugger;
            if (result.isSuccess) {
              //  console.log('$scope.getUserProfile success');
                $scope.userItem = {};
                $scope.userItem.avatar = result.data.avatar;
                $scope.userItem.name = result.data.name;
                $scope.userItem.userId = result.data.userId;
                prms.resolve();
            }
            else {
              //  console.log('$scope.getUserProfile failure');
                prms.reject();
            }

        }).error(function (result, status) {
           // console.log('$scope.getUserProfile error');
            defer.reject();
        });
        return prms;
    }

    //如果获取列表等信息失败，则返回登录页
    $scope.returnLogin = function () {
        // console.log('$scope.returnLogin');
        window.location.href = "login.html";
    }

    //设置遮幕
    $scope.isFullVisible = function () {
        $scope.isLoading = false;
        //$scope.g_timer.start();
    }

    //顺序执行获取列表信息等事件
    //$scope.getApp()
    //    .then($scope.getUserProfile, $scope.returnLogin)
    //    .then($scope.getNavList, $scope.returnLogin)
    //    .then($scope.isFullVisible, $scope.returnLogin);
    $scope.getApp()
        .then($scope.getNavList, $scope.returnLogin)
        .then($scope.isFullVisible, $scope.returnLogin);

    //是否为活动的节点
    $scope.checkActiveStatus = function (item) {
        if ($scope.activedLeafNode == item) {
            return true;
        }
        return false;
    }

    //给数组每一项（子项）加上isactive属性
    $scope.addActive = function (itemArr) {
        //debugger;

        var isNull = $scope.checkItemsLength(itemArr);

        if (isNull) {
            angular.forEach(itemArr, function (data) {
                if (data != $scope.activedLeafNode) {
                    data.isActive = false;
                } else {
                    data.isActive = true;
                }
                $scope.addActive(data.items);
                //  console.log(data.Active);
            });

        } else {
            return;
        }
    }

    //判断数组是否为空，itemArr为需要判断数组，若为空返回false，不为空返回true
    $scope.checkItemsLength = function (itemArr) {
        // debugger;
        if (itemArr == null || itemArr.length == 0) {
            return false;
        } else {
            return true;
        }
    }

    $scope.viewSwitched = function (view, viewStack) {
        $scope.viewStack = viewStack;
        $scope.$apply();
    }

    cppei.registerViewSwitched($scope.viewSwitched);

    // 从导航链接上点击
    // @subitem：当前选中的导航项
    // @ifreamScr：ifream链接地址
    $scope.onNavItemClick = function (currItem, ifreamScr) {
        if (currItem.items != null && currItem.items.length > 0) {
            return;
        }

        $scope.activedLeafNode = currItem;

        $scope.addActive($scope.items);

        var rootItems = $scope.items;

        var returnPath = [];
        $scope.traverseMenuItems(rootItems, currItem, returnPath);
        //debugger;
        angular.forEach(returnPath, function (data) {
            data.isActive = true;
        });

        cppei.switchView(currItem.caption, ifreamScr);
    }

    //查找活动节点的路径
    $scope.traverseMenuItems = function (rootItems, curItem, returnPath) {
        for (var index = 0; index < rootItems.length; index++) {
            if (rootItems[index] == curItem) {
                // find
                returnPath.push(rootItems[index]);
                return true;
            } else {
                if (rootItems[index].items != null && rootItems[index].items.length > 0) {
                    // has children in this item
                    returnPath.push(rootItems[index]);
                    var isFound = $scope.traverseMenuItems(rootItems[index].items, curItem, returnPath);
                    if (isFound) {
                        return true;
                    }
                }
            }
        }
        returnPath.pop();
        return false;
    }

    //
    $scope.hasSubItems = function (item) {
        //debugger;
        if (item.items == null || item.items.length == 0) {
            return 'hidden';
        } else {
            return 'visible';
        }
    }

    //
    $scope.hasSubItems2Bool = function (item) {
        //debugger;
        if (item.items == null || item.items.length == 0) {
            return false;
        } else {
            return true;
        }
    }

    //退出
    $scope.logout = function () {
        $http({
            method: 'post',
            url: cppei.api.getUrl('xweb', 'user', 'logout'),
            // data: {}
        }).success(function (result, status) {
            if (result.isSuccess) {
                window.location.href = "login.html";
            }
        }).error(function (result, status) {
            cppei.growl(result.message);
        });

    }

    //获取信息
    $scope.getMessage = function () {
      //  console.log('$scope.getMessage begin');
        $http({
            method: 'get',
            url: cppei.api.getUrlWithTimespan('WorkItem', 'QuerySummary'),
        }).success(function (result, status) {
            if (result.isSuccess) {
                //var time = new Date().getSeconds();
                //var testList = [{ from: 'Tom', title: 'test1', num: '65%' },
                //{ from: 'John', title: 'testTitlr1', num: '40%' },
                //{ from: 'Lily', title: 'testsss1', num: '80%' } ];
               // console.log('$scope.getMessage success');
                $scope.taskItem = {};
                $scope.taskItem.totalCount = result.data.task.totalCount;
                $scope.taskItem.unRead = result.data.task.unreadCount;
                $scope.taskList = result.data.task.items;//id,title,isRead,progress,createdTime
                angular.forEach($scope.taskList, function (value) {
                    value.progress = value.progress + '%';
                });

                $scope.alertItem = {};
                $scope.alertItem.totalCount = result.data.alert.totalCount;
                $scope.alertItem.unRead = result.data.alert.unreadCount;
                $scope.alertList = result.data.alert.items; //id,title,isRead,count,createdTime

                $scope.messItem = {};
                $scope.messItem.totalCount = result.data.message.totalCount; 
                $scope.messItem.unRead = result.data.message.unreadCount; 
                $scope.messList = result.data.message.items; //id,title,isRead,senderId,senderText,createdTime
            }
            else {
              //  console.log('$scope.getMessage failure');
                prms.reject();
            }
        }).error(function (result, status) {
           // console.log('$scope.getMessage error');
        });

    }

   //定时刷新
    $scope.g_timer = new timer(function () {
        $scope.$apply(function () {
            $scope.getMessage();
        });
    });
});
